const router = require("express")();
const dm = require("../core/DataManager");
const um = require("../core/UserManager");

router.get('/get', um.middle_finder, um.middle_loadUser, async (req, res) => {
    let tid = req.query.tid;
    dm.getThread(tid, DM_RES(res, undefined, undefined, async r => {
        if (req.user) r.hasLike = await dm.hasThreadLike(req.user.uid, tid);
        return r;
    }));
});

router.get('/tags', (req, res) => {
    let tags = req.query.tags;
    if (tags) return dm.getTags(tags, DM_RES(res));
    let tid = req.query.tid;
    dm.getThreadTag(tid, DM_RES(res, undefined, undefined, dm.getTags));
});

router.get('/like', um.middle_checker, um.middle_loadUser, (req, res) => {
    let type = req.query.type;
    if (type === 'thread') {
        let tid = req.query.tid;
        let uid = req.user.uid;
        let cancel = req.query.mode === 'cancel';
        dm.setThreadLike(cancel ? -uid : uid, tid, DM_RES(res));
    } else {
        res.json(RES_CHECKER({ success: false, err: 'Unknown Type' }));
    }
});

router.get('/search-tag/:x', (req, res) => dm.searchTag(req.params.x, DM_RES(res)));

const thread_see1 = [0, 1, 3, 4].join( /*用户自己看自己*/ );
const thread_see2 = [0, 1, 2, 3, 4, 5, 6].join( /*管理员*/ );
const thread_see3 = [0, 1, 3, 4].join( /*其他普通用户*/ );
router.get('/list', um.middle_finder, um.middle_loadUser, async (req, res) => {
    let p = req.query;
    let type = (p.type || "").trim().toLowerCase();
    let uid = p.uid;
    let index = p.index;
    let page = p.page || 0;
    let permission = um.permissionCheck(true, req.user, 'see_private_thread') ? thread_see2 : (uid && req.user && uid == req.user.uid ? thread_see1 : thread_see3);
    switch (type) {
        case "usr":
            return dm.listUserThread(uid, permission, page, DM_RES(res));
        case "new":
            {
                index = parseInt(index);
                if (index !== 1 && index !== 2) index = 0;
                return dm.listNewsThread(index, permission, page, DM_RES(res));
            }
    }
    res.end();
});


router.get('/my-count', um.middle_checker, um.middle_loadUser, (req, res) => {
    dm.userThreadCount(req.user.uid, DM_RES(res, 'count'));
});

//模块导出
module.exports = router;